package com.example.loginprojectbackend.service.impl;

import com.example.loginprojectbackend.mapper.UserMapper;
import com.example.loginprojectbackend.pojo.User;
import com.example.loginprojectbackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.mail.MailSender;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Value("${spring.mail.username}")
    String from;
    MailSender mailSender;
    StringRedisTemplate template;
    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        return userMapper.getByNameAndPassword(user);
    }

    /**
     * 查询所有用户
     * @return
     */
    @Override
    public Object getAllUser() {
        List<User> list = userMapper.getAllUser();
        return list;
    }
    /*
     * 发送邮件实现步骤：
     * 1.生成对应的键值对
     * 2.将邮箱和对应的验证码放在Redis中（过期时间三分钟,时间低于两分钟可以重新发送）
     * 3.发送验证码到指定邮箱
     * 4.发送失败，将redis中插入到值删除
     * 5.用户在注册时，再从Redis中去除对应键值对看验证码是否一致*/
    @Override
    public String sendValidateEmail(String email,String sessionId,boolean hasUser) {
        String key = "email:"+sessionId+":"+email+":"+hasUser; //防止用户在注册账号页面获取验证码，在重置密码界面填写获取的验证码
        System.out.println("发送邮件key"+key);
        if(Boolean.TRUE.equals(template.hasKey(key))){
            Long expire= Optional.ofNullable(template.getExpire(key, TimeUnit.SECONDS)).orElse(0L);
            if(expire>120)
                return "频繁操作，请稍后再试";
        }
        User user=userMapper.getByEmail(email);
        if(hasUser&&user==null)  return "没有账户使用该邮箱";
        if(!hasUser&&user!=null) return "此邮箱已被其他用户使用";
        Random random=new Random();
        int code= random.nextInt(890000)+100000;
        SimpleMailMessage message=new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject("教学成果管理系统验证邮件");
        message.setText("验证码为"+code+"用于教学成果管理系统邮箱验证，3分钟内有效，请勿泄露和转发。如非本人操作，请忽略该邮件。");
        try{
            mailSender.send(message);
            template.opsForValue().set(key,String.valueOf(code),3, TimeUnit.MINUTES);
            return null;
        }catch(MailException e){
            e.printStackTrace();
            return "邮件发送失败，请检查邮件是否有效";
        }

    }

    public String validateOnly(String email,String code,String sessionId) {

        String key = "email:" + sessionId + ":" + email + ":true";
        log.info("验证码验证key"+key);
        // if (Boolean.TRUE.equals(template.hasKey(key))) {
        String s = template.opsForValue().get(key);
        // 添加这一行来打印从Redis中取出的验证码值
        log.info("从Redis中取出的验证码值为: {}", s);
        if (s == null)
            return "验证码失效，请重新获取验证码";
        if (s.equals(code)) {
            template.delete(key);//验证码用完之后清除
            return null;
        } else {
            return "验证码错误，请检查后提交";
        }

//        } else {
//            return "请先完成邮箱验证";
//        }
    }

    @Override
    public boolean resetPassword(String password, String email) {

        return userMapper.resetPasswordByEmail(password,email)>0;
    }
    @Override
    public boolean resetInformationByJobNumber(String password, String jobNumber,String email,Integer first) {

        return userMapper.resetInformation(password,jobNumber,email,first)>0;
    }
}
